package com.yyw.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyw.common.utils.PageUtils;
import com.yyw.common.utils.Query;
import com.yyw.gulimall.product.dao.BrandDao;
import com.yyw.gulimall.product.entity.BrandEntity;
import com.yyw.gulimall.product.service.BrandService;
import com.yyw.gulimall.product.service.CategoryBrandRelationService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("brandService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    /**
     * 品牌分类接口
     */
    private final CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.lambda().like(BrandEntity::getName, key).or()
                    .eq(BrandEntity::getFirstLetter, key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params), queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateCascade(BrandEntity brand) {
        // 修改自身
        this.updateById(brand);
        // TODO: 2020/11/3  修改关联的表
        // 修改品牌分类表
        if (!StringUtils.isEmpty(brand.getName())) {
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
        }
    }

    @Override
    public List<BrandEntity> getByIds(List<Long> brandIds) {
        if (!CollectionUtils.isEmpty(brandIds)) {
            return this.listByIds(brandIds);
        }
        return new ArrayList<>();
    }

}